package com.defangit.production.orm.listeners;

import com.defangit.production.domain.StockAlteration;
import org.hibernate.event.spi.PostInsertEvent;
import org.hibernate.event.spi.PostInsertEventListener;
import org.hibernate.persister.entity.EntityPersister;

import java.time.LocalDateTime;

public class StockAlterationListener implements PostInsertEventListener{


    @Override
    public void onPostInsert(PostInsertEvent event) {
        if (event.getEntity() instanceof StockAlteration){
            StockAlteration alteration = (StockAlteration) event.getEntity();
            String query = null;
            if (alteration.getFlag()==0) query = "refreshStockForAdd";
            if (alteration.getFlag()==1) query = "refreshStockForReduce";
            alteration.setCreateTime(LocalDateTime.now());
            event.getPersister()
                    .getFactory()
                    .getCurrentSession()
                    .getNamedQuery(query)
                    .setParameter("manufacture",alteration.getManufacture().getId())
                    .setParameter("store",alteration.getStore().getId())
                    .executeUpdate();
        }

    }

    @Override
    public boolean requiresPostCommitHanding(EntityPersister persister) {
        return false;
    }
}
